require('./connect.js')
const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
  age: Number,
  email: String,
  hobbies: [String],
  name: String,
  password: String,
})
const User = mongoose.model('User', userSchema)

function findAll(content) {
  User.find()
    .select(content) // 输入要查询的属性，不要查询的属性前加-
    .then((result) => console.log('查询成功', result))
    .catch((e) => console.log('查询失败', e))
}
// findAll()
// findAll('name email -_id')

function findUsersBy(obj) {
  // 查询结果是一个数组，为空时返回[]
  User.find(obj)
    .then((result) => console.log('查询成功', result))
    .catch((e) => console.log('查询失败', e))
}
// findUsersBy({ _id: '5c09f267aeb04b22f8460968' })
// findUsersBy({ password: '123456324' })
// findUsersBy({ age: { $gt: 20, $lt: 50 } })
// findUsersBy({ hobbies: { $in: ['敲代码'] } })

function findUserBy(obj) {
  // 查询结果是一个对象，为空时返回null
  User.findOne(obj)
    .then((result) => console.log('查询成功', result))
    .catch((e) => console.log('查询失败', e))
}
// findUserBy({ password: '123456' })

function findUsersbySort(sort) {
  User.find()
    .sort(sort) // 降序排列在属性前加-
    .then((result) => console.log('查询成功', result))
    .catch((e) => console.log('查询失败', e))
}
// findUsersbySort('age')
// findUsersbySort('-age')

function findUsersbyPage(page, size) {
  User.find()
    .select('name')
    .skip(Math.max(0, page - 1) * size)
    .limit(size)
    .then((result) => console.log('查询成功', result))
    .catch((e) => console.log('查询失败', e))
}
// findUsersbyPage(1, 2)
// findUsersbyPage(2, 2)
// findUsersbyPage(3, 2)


